<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表展示区 -->
    <el-card class="box-card">
      <el-button type="primary" class="addUser" @click="dialogVisible = true"
        >添加用户</el-button
      >
      <el-table :data="rolesList" border style="width: 100%" stripe >
        <!-- 展开列 -->
        <el-table-column type="expand" >
          <template slot-scope="scope">
            <el-row
              :class="['borderBottom', i1 === 0 ? 'borderTop' : '', 'vcenter']"
              v-for="(itme1, i1) in scope.row.children"
              :key="itme1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, itme1.id)">
                  {{ itme1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'borderTop', 'vcenter']"
                  v-for="(itme2, i2) in itme1.children"
                  :key="itme2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, itme2.id)"
                    >
                      {{ itme2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="itme3 in itme2.children"
                      :key="itme3.id"
                      closable
                      @close="removeRightById(scope.row, itme3.id)"
                    >
                      {{ itme3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="removeRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showSetDialog(scope.row)"
              >分配</el-button
            >
          </template>
        </el-table-column>
      </el-table></el-card
    >
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"     
      @close="addRoleClose"
    >
      <el-form :model="addRoleForm" ref="addRoleFormRef" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="30%">
      <el-form :model="editForm" ref="editFormRef" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        class="tree"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
        
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      dialogVisible: false,
      editDialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {},
      //    添加角色表单验证规则
      //   addRoleFormRules: {
      //     roleName: [
      //       { required: true, message: '请输入角色名称', trigger: 'blur' },
      //       { min:1, max:16, message: '请输入1-16位的角色名称', trigger: 'blur' },
      //     ],
      //     roleDesc:[
      //           { required: true, message: '请输入角色描述', trigger: 'blur' },
      //       { min: 1, max: 16, message: '请输入1-16位的角色描述', trigger: 'blur' },
      //     ],
      //     },
      // 修改用户表单验证规则
      // editFormRules:{
      //       roleName: [
      //   { required: true, message: '请输入角色名称', trigger: 'blur' },
      //   { min:1, max:16, message: '请输入1-16位的角色名称', trigger: 'blur' },
      // ],
      // roleDesc:[
      //       { required: true, message: '请输入角色描述', trigger: 'blur' },
      //   { min: 1, max: 16, message: '请输入6-16位的角色描述', trigger: 'blur' },
      // ],
      // },
      //   分配权限对话框隐藏
      setRightDialogVisible: false,
      //   所有权限数据
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //   默认选中节点的id值数组
      defKeys: [],
      //   当前分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data

      this.$message.success('获取角色列表成功')
    },
    // 添加用户请求
    addRole() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')

        this.dialogVisible = false
        this.getRolesList()
      })
    },
    // 重置添加用户表单
    addRoleClose() {
      this.addRoleForm = {}
      this.$refs.addRoleFormRef.resetFields()
    },
    // 发起修改用户请求
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('修改用户失败')
      }
      this.editForm = res.data
      console.log(this.editForm)
    },
    // 重置修改用户表单
    editClose() {
      this.editForm = {}
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改用户请求
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改用户失败')
        }
        this.$message.success('修改用户成功')
        // 关闭对话框
        this.editDialogVisible = false
        //  刷新列表
        this.getRolesList()
      })
    },
    // 删除用户请求
    async removeRole(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消消除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('用户删除成功')
      this.getRolesList()
    },
    // 点击权限图标删除该权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除用户该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      role.children = res.data
    },

    // 点击分配按钮获取所有权限的数据
    async showSetDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取所有权限数据失败')
      }

      this.rightsList = res.data

      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys数组
    getLeafKeys(node, arr) {
      // 判断当前节点中是否有children属性，没有就添加到arr
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    setRightDialogClosed() {
      this.defKeys = []
      this.rightsList = []
      console.log(this.defKeys)
    },
    // 分配按钮 拿到所有选中 半选中节点id的方法
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      //   服务器只接收字符串类型的值,把数组转换成字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色权限失败')
      }
      this.$message.success('分配角色权限成功')

      this.getRolesList()

      this.setRightDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.box-card {
  margin-top: 20px;
}
.addUser {
  margin-bottom: 20px;
}
.borderTop {
  border-top: solid 1px #eee;
}
.borderBottom {
  border-bottom: solid 1px #eee;
}
.vcenter {
  display: flex;
  align-items: center;
  
}
.el-tag {
  margin: 10px;
}
.tree {
  border: #ccc solid 1px;
  border-radius: 10px;
  max-height: 570px;
  overflow: auto;
}
</style>
